package com.xbongbong.workflow.service.strategy.data.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.enums.TaskTypeEnum;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.AssembleProductEntity;
import com.xbongbong.saas.domain.entity.ext.AssembleEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.help.SaasSaveHelp;
import com.xbongbong.saas.model.AssembleModel;
import com.xbongbong.saas.model.AssembleProductModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.User;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy;
import com.xbongbong.workflow.service.strategy.data.WorkflowDataProcessStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 *
 * @author 魏荣杰
 *
 */
@Service
public class WorkflowAssembleStrategy extends AbstractWorkflowDataStrategy implements WorkflowDataProcessStrategy {

    private static final Logger log = LoggerFactory.getLogger(WorkflowAssembleStrategy.class);

    @Resource
    private SaasSaveHelp saasSaveHelp;
    @Resource
    private AssembleModel assembleModel;
    @Resource
    private UserModel userModel;
    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private AssembleProductModel assembleProductModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;

    @Override
    public List<Integer> type() {
        return Collections.singletonList(XbbRefTypeEnum.ASSEMBLE.getCode());
    }

    @Override
    public void save(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜保存
        saveDataCabinetFile(workflowTransferPOJO);

        String corpid = workflowTransferPOJO.getCorpid();
        Data pojoData = workflowTransferPOJO.getData();
        JSONObject data = pojoData.getData();
        Long dataId = pojoData.getId();
        Integer businessType = pojoData.getBusinessType();
        User user = workflowTransferPOJO.getUser();
        UserEntity userEntity = userModel.getByKeyIngoreDel(user.getUserId(), corpid);
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(userEntity, userVO);


        AssembleEntityExt assembleEntityExt = assembleModel.getByKey(dataId, corpid);
        assembleEntityExt.setData(data);
        SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
        saasFormSaveDTO.setCorpid(corpid);
        saasFormSaveDTO.setBusinessType(businessType);
        saasFormSaveDTO.setOldData(data);
        saasFormSaveDTO.setNewData(data);
        saasFormSaveDTO.setNewPaasFormDataEntity(assembleEntityExt);
        saasFormSaveDTO.setOldPaasFormDataEntity(assembleEntityExt);
        saasFormSaveDTO.setIsNew(true);
        saasFormSaveDTO.setIsImport(workflowTransferPOJO.getIsImport());
        saasFormSaveDTO.setCostMap(new HashMap<>());
        saasFormSaveDTO.setLoginUser(userVO);
        saasFormSaveDTO.setUserId(user.getUserId());
        saasFormSaveDTO.setLoginUserName(user.getName());
        saasFormSaveDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());

        saasSaveHelp.generateStockSheet(saasFormSaveDTO);
        addLinkDataDynamic(workflowTransferPOJO);
        // api
        apiHook(workflowTransferPOJO);
        // log
        afterSaveLog(workflowTransferPOJO);
    }

    @Override
    public void update(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜保存
        saveDataCabinetFile(workflowTransferPOJO);

        // api
        apiHook(workflowTransferPOJO);
        // log
        afterUpdateLog(workflowTransferPOJO);
    }

    @Override
    public void updateBack(Long taskId, WorkflowTransferPOJO workflowTransferPOJO) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Long backupDataId = workflowTransferPOJO.getBackupDataId();
            Long dataId = workflowTransferPOJO.getData().getId();
            WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(backupDataId, corpid);
            if (Objects.nonNull(workflowBackupDataEntity)) {
                JSONObject data = workflowBackupDataEntity.getData();

                replenishAttrForBackupData(workflowTransferPOJO.getData().getData(), data);

                AssembleEntityExt assembleEntityExt = new AssembleEntityExt();
                assembleEntityExt.setId(dataId);
                assembleEntityExt.setCorpid(corpid);
                assembleEntityExt.setData(data);
                assembleEntityExt.setSerialNo(data.getString(FieldTypeEnum.SERIALNO.getAlias()));
                // 获取负责人
                assembleEntityExt.setOwnerId(getOwnerId(data));
                assembleEntityExt.setDepartmentId(data.getLong(FieldTypeEnum.DEPARTMENTID.getAlias()));
                List<AssembleProductEntity> list = JSON.parseArray(data.getString(StringConstant.PRODUCT), AssembleProductEntity.class);

                FormDataUtil.removeSystemData(data);
                data.remove(StringConstant.PRODUCT);
                if (Objects.equals(workflowTransferPOJO.getOperate(), WorkflowOperateEnum.UPDATE.getType())) {
                    assembleEntityExt.setFlowStatus(FlowStatusEnum.PASS.getType());
                }
                assembleModel.update(assembleEntityExt);

                // 回退被删掉的子表单
                updateBackSubForm(assembleEntityExt, corpid, IndexTypeEnum.IDX_SAAS_ASSEMBLE_SUB);
                //回退被删掉的富文本
                updateBackRichText(taskId, workflowTransferPOJO);
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowAssembleStrategy.updateBack error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public void approvalFailed(Long taskId, WorkflowTransferPOJO workflowTransferPOJO, Integer taskType) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Data workflowData = workflowTransferPOJO.getData();
            Long dataId = workflowData.getId();
            Long formId = workflowData.getFormId();
            Integer businessType = workflowData.getBusinessType();
            Integer saasMark = workflowData.getSaasMark();
            AssembleEntityExt assembleEntityExt = new AssembleEntityExt();
            assembleEntityExt.setId(dataId);
            if (Objects.equals(TaskTypeEnum.REVOKE.getType(), taskType)) {
                assembleEntityExt.setFlowStatus(FlowStatusEnum.REVOKE.getType());
            } else {
                assembleEntityExt.setFlowStatus(FlowStatusEnum.REJECT.getType());
            }
            assembleEntityExt.setCorpid(corpid);
            assembleEntityExt.setUpdateTime(DateTimeUtil.getInt());
            assembleModel.update(assembleEntityExt);
            // 子表单
            DelEnum del = DelEnum.APPROVE_FAILED;

            paasFormSubDataModel.deleteBatchByDataId(Collections.singletonList(dataId), corpid, IndexTypeEnum.IDX_SAAS_ASSEMBLE_SUB, del);

            //富文本
            deleteFormRichText(dataId, corpid, formId, businessType, saasMark, DelEnum.NORMAL);

            // 关联产品
            List<AssembleProductEntity> productList = assembleProductModel.getProductsByAssembleId(dataId, corpid);
            if (CollectionsUtil.isNotEmpty(productList)) {
                List<Long> idList = new ArrayList<>();
                productList.forEach(item->idList.add(item.getId()));
                assembleProductModel.deleteBatch(idList, corpid, del.getDel());
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowAssembleStrategy.approvalFailed error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    private void saveProduct(List<AssembleProductEntity> list, String corpid) throws XbbException {

        if (CollectionsUtil.isNotEmpty(list)) {
            assembleProductModel.updateBatch(list, corpid);
        }

    }

}
